<template>
  <div>
    <el-dialog :title="title"
               :visible.sync="visible"
               v-loading="loading"
               :before-close="modalClose"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="80%">
      <el-form ref="formRef"
               :model="formModel"
               :rules="formRules"
               label-width="140px">
        <el-form-item label="权益主体："
                      prop="companyId">
          <el-select v-model="formModel.companyId"
                     placeholder="请选择权益主体"
                     filterable
                     remote
                     reserve-keyword
                     clearable
                     :remote-method="(query) => {remoteMethod(query, 'headOffice')}"
                     :loading="loading1"
                     class="w-200"
                     @change="val=>handleSelect(val, 'headOffice')">
            <el-option v-for="item in headOfficeFilterList"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与分店：">
          <el-table :data="tableBranch"
                    border
                    style="width: 100%"
                    @selection-change="handleSelectionChange"
                    ref="asTable"
                    height="460">
            <el-table-column width="50"
                             type="selection"
                             fixed="left">
            </el-table-column>
            <el-table-column prop="id"
                             label="ID">
            </el-table-column>
            <el-table-column prop="hospitalId"
                             label="医院ID">
            </el-table-column>
            <el-table-column prop="hospitalName"
                             label="分店名字">
            </el-table-column>
            <el-table-column prop="manager"
                             label="店长">
            </el-table-column>
            <el-table-column prop="phone"
                             label="联系方式">
            </el-table-column>
          </el-table>
          <p align="left"
             class="mt-20">
            已选：{{ allMultipleSelection }}
            <el-pagination background
                           @current-change="handleCurrentChange"
                           :current-page.sync="pagination.pageIndex"
                           :page-size="pagination.pageSize"
                           layout="total, prev, pager, next, jumper"
                           :total="pagination.totalNum">
            </el-pagination>
          </p>
        </el-form-item>
        <el-form-item label="有效期："
                      prop="time">
          <el-date-picker v-model="formModel.time"
                          type="datetime"
                          value-format="yyyy-MM-dd hh:mm:ss"
                          placeholder="请选择有效期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="每月每店回访次数："
                      prop="count">
          <el-input-number v-model="formModel.count"
                           placeholder="请输入回访次数"
                           :controls="false"
                           :min="0"
                           clearable
                           class="w-200"></el-input-number>
        </el-form-item>
        <el-form-item label="每店权益配置："
                      prop="equityType">
          <el-radio-group v-model="formModel.equityType"
                          @change="handleChangeType">
            <el-radio-button :label="1">抵用券</el-radio-button>
            <el-radio-button :label="2">耗 材</el-radio-button>
          </el-radio-group>
          <el-button type="primary"
                     style="margin-left:20px;"
                     plain
                     @click="dialogVisible = true">新 增</el-button>
          <el-table :data="formModel.equityType === 1 ? tableCoupon : tableTestPaper"
                    style="width: 100%"
                    border
                    class="mt-20">
            <template v-if="formModel.equityType === 1">
              <el-table-column prop="coupon"
                               label="抵扣券金额">
              </el-table-column>
              <el-table-column prop="couponNum"
                               label="数量">
              </el-table-column>
              <el-table-column prop="range"
                               label="适用范围">
              </el-table-column>
            </template>
            <template v-if="formModel.equityType === 2">
              <el-table-column prop="testPaper"
                               label="试纸名称">
              </el-table-column>
              <el-table-column prop="testPaperNum"
                               label="数量">
              </el-table-column>
            </template>

            <el-table-column prop="option"
                             label="操作"
                             width="120"
                             align="center">
              <template slot-scope="scope">
                <el-button type="danger"
                           @click="delRow(formModel.equityType === 1 ? tableCoupon : tableTestPaper, scope.$index)">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <p align="center">
        <el-button @click="modalClose"
                   type="primary">取 消</el-button>
        <el-button @click="submitForm"
                   type="primary">保 存</el-button>
      </p>
    </el-dialog>

    <el-dialog :title="title"
               :visible.sync="dialogVisible"
               width="30%"
               @close="dialogVisible = false">
      <el-form ref="formDataRefs"
               :model="formData"
               :rules="formDataRules"
               label-width="120px">
        <template v-if="formModel.equityType === 1">
          <el-form-item label="抵扣券："
                        prop="coupon">
            <el-select v-model="formData.coupon"
                       placeholder="请选择抵扣券">
              <el-option v-for="item in couponList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="抵扣券数量："
                        prop="couponNum">
            <el-input v-model="formData.couponNum"
                      class="w-200"
                      placeholder="请输入抵扣券数量"></el-input>
          </el-form-item>
        </template>
        <template v-if="formModel.equityType === 2">
          <el-form-item label="试纸名称："
                        prop="testPaper">
            <el-select v-model="formData.testPaper"
                       placeholder="请选择试纸名称：">
              <el-option v-for="item in testPaperList"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="试纸数量："
                        prop="testPaperNum">
            <el-input v-model="formData.testPaperNum"
                      class="w-200"
                      placeholder="请输入试纸数量"></el-input>
          </el-form-item>
        </template>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitData(formModel.equityType)">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>
<script>
  export default {
    props: {
      dataObj: {
        type: Object,
        default: {}
      },
      visible: {
        type: Boolean,
        default: false
      },
    },
    name: 'setEquityDialog', // 购药回访权益权益设置
    data () {
      return {
        title: '新 增',
        loading: false,
        loading1: false,
        dialogVisible: false,
        formModel: {
          id: null,
          companyId: '',
          hospitalIds: '',
          time: '', // 有效期
          count: undefined, // 每月每店回访次数
          equityType: 1, // 每店权益配置
          tableData: [],
        },
        formRules: {
          companyId: [{ required: true, message: '请选择权益主体', trigger: 'chagne' }]
        },
        formData: {
          coupon: '',
          couponNum: null,
          testPaper: '',
          testPaperNum: null,
        },
        formDataRules: {
          coupon: [{ required: true, message: '请选择抵扣券', trigger: 'chagne' }],
          couponNum: [{ required: true, message: '请输入抵扣券数量', trigger: 'blur' }],
          testPaper: [{ required: true, message: '请选择试纸', trigger: 'chagne' }],
          testPaperNum: [{ required: true, message: '请输入试纸数量', trigger: 'blur' }],
        },
        pageIndex: 1,
        pageSize: 10,
        headOfficeList: [],
        headOfficeFilterList: [],

        multipleSelection: [],
        allMultipleSelection: [],
        pagination: {
          pageIndex: 1,
          pageSize: 10
        },
        tableBranch: [],
        title: '新增抵扣券',
        // 抵扣券列表
        couponList: [
          { value: 1, label: 'xxx1' },
          { value: 2, label: 'xxx2' },
          { value: 3, label: 'xxx3' },
          { value: 4, label: 'xxx4' },
        ],
        // 试纸券列表
        testPaperList: [
          { value: 1, label: 'xxx1' },
          { value: 2, label: 'xxx2' },
          { value: 3, label: 'xxx3' },
          { value: 4, label: 'xxx4' },
        ],
        tableCoupon: [],
        tableTestPaper: [],

      }
    },
    methods: {
      modalClose () {
        this.$emit('update:visible', false); // 直接修改父组件的属性
      },

      // 远程搜索
      remoteMethod (query, type) {
        if (query !== '') {
          let _this = this;
          if (query) {
            if (type === 'headOffice') { // 参与活动客户
              _this.loading1 = true;
              this.post(this.api.company.companyList, {
                pageIndex: this.pageIndex - 1,
                pageSize: this.pageSize,
                name: query,
                hospitalType: '',
                status: 1
              }).then(res => {
                if (res.data.code === '200') {
                  _this.loading1 = false;
                  _this.headOfficeList = res.data.object;
                }
              })
              setTimeout(() => {
                _this.loading1 = false;
                _this.headOfficeFilterList = _this.headOfficeList.filter(item => item.name.indexOf(query) > -1);

              }, 200)
            }

          }
        } else {
          if (type === 'headOffice') {
            this.activeCustomersFilterList = [];
          }
        }
      },
      handleSelect (item, type) {
        if (type === 'headOffice') {
          this.formModel.companyId = item;
          this.allMultipleSelection = [];
          this.fetchData();
        }

      },
      // 查询分店
      fetchData () {
        this.post(this.api.company.hospitalList, {
          pageIndex: this.pagination.pageIndex - 1,
          pageSize: this.pagination.pageSize,
          searchCondition: '',
          companyId: this.formModel.companyId
        }).then(res => {
          if (res.data.code === '200') {
            setTimeout(_ => {
              this.tableBranch = res.data.object;
              this.pagination.totalNum = res.data.totalNum;
              if (this.tableBranch.length === 0) {
                this.$message.error('该总店下面未查询到分店,请选择其它总店!');
                this.formModel.companyId = '';
                return
              }
              // 实现分页复选
              setTimeout(_ => {
                this.setSelectedRow();
              }, 50)
            }, 200)
          }
        })
      },
      setSelectedRow () {
        // 设置当前页已选项
        this.tableBranch.forEach(item => {
          if (this.allMultipleSelection.includes(item.hospitalId)) {
            this.$refs.asTable.toggleRowSelection(item, true);
            // console.log(item.id, 'set');
          }
        })
      },
      handleCurrentChange (val) {
        this.pagination.pageIndex = val;
        this.fetchData();
      },

      handleSelectionChange (val) {
        this.multipleSelection = val;
        // 实现分页复选
        setTimeout(_ => {
          this.resolveAllSelection();
        }, 50);
      },
      resolveAllSelection () {
        let currentPageData = this.tableBranch.map(item => item.hospitalId); // 当前页所有数据
        let currentPageSelected = this.multipleSelection.map(item => item.hospitalId); // 当前页已选数据
        let currentPageNotSelected = currentPageData.filter(item => !currentPageSelected.includes(item)); // 当前页未选数据
        // 将当前页已选数据放入所有已选项
        currentPageSelected.forEach(item => {
          if (!this.allMultipleSelection.includes(item)) {
            this.allMultipleSelection.push(item);
          }
        })
        // 将所有已选项数据中当前页没选择的项移除
        currentPageNotSelected.forEach(item => {
          let idx = this.allMultipleSelection.indexOf(item);
          if (idx > -1) {
            this.allMultipleSelection.splice(idx, 1);
          }
        })
      },
      delRow (table, index) {
        table.splice(index, 1);
      },
      handleChangeType (val) {
        this.title = val === 1 ? '新增抵扣券' : '新增试纸';
      },
      // 每店权益配置
      submitData (val) {
        console.log(this.formData);
        this.$refs.formDataRefs.validate((valid) => {
          if (valid) {
            if (val === 1) {
              this.tableCoupon.push(this.formData);
            }
            if (val === 2) {
              this.tableTestPaper.push(this.formData);
            }
            this.dialogVisible = false;
          }
        })

      },
      // 提交
      submitForm () {
        this.formModel.tableData = [...this.tableCoupon, ...this.tableTestPaper];

        this.$refs['formRef'].validate((valid) => {
          if (valid) {
            if (this.multipleSelection.length === 0) {
              this.$message.error('至少勾选一家参与分店!');
              return
            }
            if (this.formModel.tableData.length === 0) {
              this.$message.error('请配置每店权益!');
              return
            }


            let params = {
              ...this.formModel,
              hospitalIds: JSON.stringify(this.allMultipleSelection),
            }
            console.log(params);
            return
            this.post(this.api.company.updateReadDoctorConfig, params).then(res => {
              if (res.data.code === '200') {
                this.$message.success('保存成功!');
                this.$parent.getList();
                this.modalClose();
              }
            })
          }
        })
      },
      getDetail () {
        this.post(this.api.company.getReadDoctorConfigDetail, {
          id: this.dataObj.id
        }).then(res => {
          if (res.data.code === '200') {
            let resData = res.data.object;
            this.formModel.id = resData.id;
            // 查询总店
            this.formModel.companyId = resData.companyId;
            setTimeout(() => { this.remoteMethod(resData.companyName, 'headOffice'); }, 1000);
            this.handleSelect(resData.companyId, 'headOffice'); // 回显分店
            this.allMultipleSelection = JSON.parse(resData.hospitalIds); // 回显选中的分店
          }
        })
      }
    },
    created () {
      if (this.dataObj) {
        this.getDetail();
        this.title = '新增抵扣券';
      }
    },
  }
</script>
<style lang="scss" scoped>
</style>